local ServerOHOH = _G.ServerOHOH;
local M = ServerOHOH.class.new(script, ServerOHOH.files.Server_PlayerComponent(),script.Parent.Name);--,script.Parent.Name
local function_list =_G.ServerOHOH.function_list
local Tool=require(script.Parent.tool)
local RecipeTool=_G.CommonOHOH.load.RecipeTool();
local fuseAmount = _G.CommonOHOH.config.Game.fuseAmount
function M.new(self,...)
	return M(self,...);
end;

function M.ctor(self, parent)
	M.super.ctor(self, parent);
    self.player=self.parent
	self.DataBase=self.parent:GetComponent(ServerOHOH.load.Server_PlayerDataComponent())
	self.decoList ={}
	print("初始化--- 工坊 （遗物、牺牲）-->")

	self.DecoEuqipUpdateEvent=self.player.DecoEuqipUpdateEvent
	if self.player.character then
        self.player.character:AddPrivateComponent(script.DecoView)
    end

    self.player.CharacterEnterEvent:Connect(function(character)
		if not self.CharacterEnter then
			self.CharacterEnter = true
			character:AddPrivateComponent(script.DecoView)
		end
           
    end)
end;

function M.RecipeMake(self,rCfg)
	assert(rCfg.itemData,"rCfg.itemData==null")
	local hadPartStore=self.DataBase:GetData("car").had
	local partTable = rCfg.itemData
	for key, value in pairs(partTable) do
		local itemName, id = Tool.Split_ItemData(key)
		if not hadPartStore[id] or hadPartStore[id]<value then
			print("材料不足")
			return false
		end
	 end

	print("材料足够,扣除砖石",rCfg)
--扣除消耗货币
	assert(rCfg.cost,"rCfg.cost==null")
	--重要！！！ 不能删
	--正式有钻石数据后启用
	local errorCode,sum,key= Tool.IsCanMakeRecipe(rCfg.cost,self.DataBase)
	if  errorCode>0 then
		print("cost 不足",sum,key)
	    return false
	end
	self.parent:GetComponent(ServerOHOH.load.Server_ItemCtrl()):AddItem({[key]=-sum},true,true)
	print("cost 足够",sum,key)

--扣除消耗材料
	for key, value in pairs(partTable) do
		local itemName, id = Tool.Split_ItemData(key)
		hadPartStore[id]=hadPartStore[id]-value
		if hadPartStore[id]==0 then
			hadPartStore[id]=nil
		end
 	end
	 self.DataBase:Execut(function()
	 end);
	 self.parent:SynchDataToClient("car")
	 

	assert(rCfg.id,"rCfg.cost==null")
	table.insert(self.DataBase:GetData("recipe").make.__real, rCfg.id)
	self.DataBase:Execut(function()
	end);
    self.parent:SynchDataToClient("recipe")
	self.player.CraftRelicEvent:Action()
    return true
end

--装备
function M.RecipeEquip(self,rCfg)
	local rId = rCfg.id
	assert( rId,"rCfg.cost==null")
	
--读取装备数据
	local equipdata = self.DataBase:GetData("recipe").equip.__real
	if equipdata then
		for i = 1, #equipdata do
			local type = RecipeTool.GetRecipeItemTypeById(equipdata[i])
			self.decoList[type] = equipdata[i]
		end
	end
--装饰点位上有物品则需要先销毁
	if self.decoList[rCfg.itemType]  then
		local oldCfg =RecipeTool.GetRecipeCfgData(self.decoList[rCfg.itemType])
		self:RecipeUnEquip(oldCfg)
	end
	
	self.decoList[rCfg.itemType]= rId

--添加新物体
	table.insert(self.DataBase:GetData("recipe").equip.__real, rId)
	self.DataBase:Execut(function()
	end);
	self.parent:SynchDataToClient("recipe")
	self.DecoEuqipUpdateEvent:Action()

	--self:ChangeRngData(rCfg,1)
	--add对应的luck值
	self.player.CraftRelicEvent:Action()
    self.player.UnlockRecipeEvent:Action()
	return true

end
--卸载
function M.RecipeUnEquip(self,rCfg)

	if self.decoList[rCfg.itemType]  then
		local  removeId = rCfg.id
		assert( removeId,"removeId==null")
		local recipeData = self.DataBase:GetData("recipe").equip.__real
		local indexToRemove = nil
		for index, value in ipairs(recipeData) do
			if value == removeId then
				indexToRemove = index
				break
			end
		end
		if indexToRemove then
			table.remove(self.DataBase:GetData("recipe").equip.__real, indexToRemove)
			self.decoList[rCfg.itemType]= nil
		end
		

		self.DataBase:Execut(function()
		end);
		self.parent:SynchDataToClient("recipe")
		self.DecoEuqipUpdateEvent:Action()
		--self:ChangeRngData(rCfg,-1)
		return true
	end
end

function M.containsValue(self,tbl, value)
    for _, v in ipairs(tbl) do
        if v == value then
            return true -- 如果找到，返回 true
        end
    end
    return false -- 如果没找到，返回 false
end
--解锁配方 参数配方id 数字
function M.RecipeUnLock(self,recipeId)
	assert( recipeId,"recipeId==null")
	local rId = recipeId

	local  rlist = self.DataBase:GetData("recipe").relic.__real
	local result = self:containsValue( rlist, rId)
	if self:containsValue( rlist, rId) then
		return
	else
		-- 如果不存在，插入新值
		table.insert(self.DataBase:GetData("recipe").relic.__real, rId)
	end

	
	self.DataBase:Execut(function()
	end);
	self.parent:SynchDataToClient("recipe")
	self.player.UnlockRecipeEvent:Action()
end


--工坊解锁 wId =  1：遗物、2：熔断 3：牺牲
function M.WorkShopUnLock(self,workShopId)
	assert(workShopId,"workShopId==null")
	local wId = workShopId
	table.insert(self.DataBase:GetData("workshop").unlock.__real, wId)
	self.DataBase:Execut(function()
	end);
	self.parent:SynchDataToClient("workshop")

end

function M.Fuse(self,list)
	local fuseList = {}
	for key, value in pairs(list) do
		fuseList[key] = value
 	end

	local hadPartStore=self.DataBase:GetData("car").had.__real
	for key, value in pairs(fuseList) do
		local newValue = Tool.Add_ItemData(value,1)
		
		while hadPartStore[value] >= fuseAmount do
			hadPartStore[value] = hadPartStore[value] - fuseAmount
			if not hadPartStore[newValue] then
				hadPartStore[newValue] = 0
			end
			hadPartStore[newValue] = hadPartStore[newValue]+1
		end

		if hadPartStore[value]==0 then
			hadPartStore[value]=nil
		end
 	end
	 self.DataBase:Execut(function()
	 end);
	 self.parent:SynchDataToClient("car")
	 print("### 服务器数据",self.DataBase:GetData("car").had.__real)
	 return true

	-- assert(workShopId,"workShopId==null")
	-- local wId = workShopId
	-- table.insert(self.DataBase:GetData("workshop").unlock.__real, wId)
	-- self.DataBase:Execut(function()
	-- end);
	-- self.parent:SynchDataToClient("workshop")

end
--工坊解锁 1：遗物、2：熔断 3：牺牲
M:RegistFunction(function_list.workshop_unlock,M.WorkShopUnLock)

--遗物制作
M:RegistFunction(function_list.recipe_make,M.RecipeMake)
--遗物装备
M:RegistFunction(function_list.recipe_equip,M.RecipeEquip)
--遗物卸下装备
M:RegistFunction(function_list.recipe_unequip,M.RecipeUnEquip)

--配方解锁（参数：配方ID）
M:RegistFunction(function_list.recipe_unlock,M.RecipeUnLock)

--熔断（参数：熔断列表）
M:RegistFunction(function_list.part_fuse,M.Fuse)

return M
